//模拟用户手动输入
window.inputValue = (dom, st) => {
  let evt = new InputEvent('input', {
    inputType: 'insertText',
    data: st,
    dataTransfer: null,
    isComposing: false
  });
  dom.value = st;
  dom.dispatchEvent(evt);
};
var type = 0
var state = false;
var rep = true;
var arr = [];
var coolingTime = 30_000//跟答冷却期
var resetTime = 15_000//跟答重置期
var ipt
var fadanmu
var close
var input
var btn
var send
var followCount = 2//重复弹幕需要达到此次数才会跟答

chrome.storage.sync.get(["follow", "reply", "who", "what"], messages => {
	setTimeout(() => {
		ipt = document.querySelector('.danmu__ipt');
		fadanmu = document.querySelector(".icon-fadanmu");
		close = document.querySelector(".send__close");
		input = document.querySelector('.send__input');
		btn = $(".send__btn");
		send = $(".danmu__send");

		if (messages['follow'] === 'true'){
			console.info('YKT->已开启自动跟答')
		}
		if (messages['reply'] === 'true'){
			console.info('YKT->已开启自动应答')
		}

		if(document.querySelector(".danmu__list")){
			type = 1
			console.info("YKT->使用第一种弹幕dom【新版】")
			//自动跟答
			$(".danmu__list").attr("id", "listener2");
			document.getElementById("listener2").addEventListener("DOMNodeInserted",() => {
				let content = $(".danmu__list>li:last").text();
				follow(messages, content)
			})
		}else if(document.querySelector(".danmu-live")){
			type = 2
			console.info("YKT->使用第二种弹幕dom【老版】")
			$(".danmu-live").attr("id", "listener2");
			//自动跟答
			document.getElementById("listener2").addEventListener("DOMNodeInserted",() => {
				let content = $(".danmu-live>div>div:last").text();
				follow(messages, content)
			})
		}else{
			// 若两种弹幕dom都没发现，则提醒使用者
			chrome.runtime.sendMessage("no", function(message){});
			console.info("YKT->弹幕未打开或弹幕类型不支持，功能无法正常使用");
		}


		// 监听点名
		$(".timeline__wrap").attr("id","listener1");
		let who = messages["who"] ? messages["who"] : "点名";
		let what = messages["what"] ? messages["what"] : "在";
		let antiDuplication = false;
		document.getElementById("listener1").addEventListener("DOMNodeInserted",() => {
			if(antiDuplication){
				return;
			}
			antiDuplication=true;
			setTimeout(() => {
				antiDuplication=false;
			},200)//冷却时间

			const list = document.querySelectorAll(".timeline__item");
			let len = list.length;
			const last = $(list[len - 1]);
			let lastDom = last.text();
			if(lastDom.indexOf(who) !== -1){
				chrome.runtime.sendMessage("point",msg => {})
				console.info("YKT->点名点到你了：" + who);
				if(messages["reply"] === "true"){
					sendText(what)
					console.info("YKT->已经应答：" + what);
				}
			}else if (lastDom.indexOf("下课啦") !== -1){
				chrome.runtime.sendMessage("over",function(message){
					location.href="https://www.yuketang.cn/v2/web/index";
				});
			}else if($(last).children("div[class='timeline__ppt problem']").text() !== ""){
				chrome.runtime.sendMessage("question",function(message){});
			}else if(lastDom.indexOf("开启弹幕") !== -1){
				location.reload();
			}else if (lastDom.indexOf("关闭弹幕") !== -1){
				chrome.runtime.sendMessage("close",function(message){});
			}else{
				console.info(`YKT->${lastDom}，没点到你，` + new Date().toLocaleString());
			}
		})
	},2000)

});

//发送弹幕
function sendText(msg){
	if (type === 1){
		window.inputValue(ipt,msg)
		send.trigger("click")
	}else{
		fadanmu.click()
		window.inputValue(input,msg)
		btn.trigger("click");
		close.click()
	}
}

function follow(messages, content){
	console.info(`YKT->弹幕：${content}`)
	if (messages['follow'] === 'true'){
		if(!rep){
			return;
		}
		if(!state){
			arr=[];
			state=true;
			setTimeout(function(){
				console.info("YKT->弹幕记录重置");
				state=false;
			},resetTime)
		}
		if(content.indexOf("(我)") !== -1 || content.indexOf("在") === 0 || content.indexOf("在") === content.length - 1){
			return;
		}
		let count = 0
		for (let i = 0; i < arr.length; i++) {
			if(arr[i] === content && ++count === followCount){
				state=false;
				rep=false;
				setTimeout(() => {
					rep=true;
					console.info("YKT->跟答冷却期结束")
				},coolingTime)//冷却时间
				sendText(content)
				console.info(`YKT->已经跟答：${content}，进入跟答冷却期 ${coolingTime / 1000}s`);
			}
		}
		if (count < followCount){
			arr.push(content);
		}
	}
}